package main

import (
	"fmt"
	"net"
	"strings"
)

func main() {
	Listener, err := net.Listen("tcp", "localhost:8000")
	if err != nil {
		fmt.Println("err = ", err)
		return
	}
	defer Listener.Close()

	//接收多个用户
	for {
		conn, err := Listener.Accept()
		if err != nil {
			fmt.Println("err = ", err)
			return
		}
		//处理多用户请求 为每个用户创建一个go协程
		go HandleConn(conn)
	}

}

//处理请求
func HandleConn(conn net.Conn) {
	defer conn.Close()
	//获取客户端的网络地址信息
	addr := conn.RemoteAddr().String()
	fmt.Println("addr connect sucessful")
	buf := make([]byte, 2048)

	//循环读取
	for {
		//读取用户数据
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println("err = ", err)
			return
		}
		fmt.Println("addr = ", addr, " read buf = ", string(buf[:n]))
		if "exit" == string(buf[:n-2]) {
			fmt.Println("exit")
			return
		}
		//把数据转换成大写再发送给用户
		conn.Write([]byte(strings.ToUpper(string(buf[:n]))))
	}
}
